package com.poc.etmart.daos;

import java.util.Date;
import java.util.Iterator;
import java.util.List;

import javax.persistence.EntityManager;
import javax.persistence.EntityTransaction;
import javax.persistence.Query;

import com.poc.etmart.entity.MartAlerts;
import com.poc.etmart.entity.PostedItems;
import com.poc.etmart.entity.ReplyPosts;


public class ETMartDao {
//	private static final EntityManagerFactory EMF = Persistence.createEntityManagerFactory("transactions-optional");
	
	public boolean insertIntoMartAlerts(MartAlerts martAlerts){
		EntityManager em = EMF.get().createEntityManager();
		EntityTransaction tx = em.getTransaction();

		try {
			tx.begin();
			em.persist(martAlerts);
			tx.commit();
		} finally {
			if (tx.isActive()) {
				tx.rollback();
			}
			em.close();
		}
		
		return false;
	}
	public boolean insertIntoPostedItems(PostedItems postedItems){
		EntityManager em = EMF.get().createEntityManager();
		EntityTransaction tx = em.getTransaction();
		System.out.println("inside");
		try {
			tx.begin();
			postedItems.setCreatedDt(new Date());
			postedItems.setPostedItemsId(getNxtPosItmId());
			em.persist(postedItems);
			tx.commit();
		} finally {
			if (tx.isActive()) {
				tx.rollback();
			}
			em.close();
		}
		
		return false;
	}
	public boolean insertIntoReplyPosts(ReplyPosts replyPosts){
		EntityManager em = EMF.get().createEntityManager();
		EntityTransaction tx = em.getTransaction();
		System.out.println("inside");
		try {
			tx.begin();
			replyPosts.setCreatedDt(new Date());
			replyPosts.setReplyPostsId(getNxtReplyPostsId());
			em.persist(replyPosts);
			tx.commit();
		} finally {
			if (tx.isActive()) {
				tx.rollback();
			}
			em.close();
		}
		
		return false;
	}
	public int getNxtPosItmId() {
		EntityManager em = EMF.get().createEntityManager();
		Query query = em
				.createQuery("select postedItemsId from PostedItems pi order by createdDt desc");
		@SuppressWarnings("unchecked")
		List<Integer> results = query.getResultList();
		Iterator<Integer> piIte =  results.iterator();
		int lastPiId = 1;
		if(piIte.hasNext()){
			int objPI = piIte.next();
			lastPiId = objPI+1;
		}
		return lastPiId;
	}
	public int getNxtReplyPostsId() {
		EntityManager em = EMF.get().createEntityManager();
		Query query = em
				.createQuery("select replyPostsId from com.poc.etmart.entity.ReplyPosts pi order by CreatedDt desc");
		@SuppressWarnings("unchecked")
		List<Integer> results = query.getResultList();
		Iterator<Integer> piIte =  results.iterator();
		int lastPiId = 1;
		if(piIte.hasNext()){
			int objPI = piIte.next();
			lastPiId = objPI+1;
		}
		return lastPiId;
	}
}
